package com.visionet.waveletData.web.web.account;

import com.google.common.collect.Maps;
import com.visionet.waveletData.web.common.constant.BusinessStatus;
import com.visionet.waveletData.web.common.utils.CookieUtil;
import com.visionet.waveletData.web.entity.account.User;
import com.visionet.waveletData.web.service.account.AccountService;
import com.visionet.waveletData.web.service.account.ShiroDbRealm.ShiroUser;
import com.visionet.waveletData.web.web.BaseController;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * LoginController负责打开登录页面(GET请求)和登录出错页面(POST请求)，

 * 真正登录的POST请求由Filter完成,
 * 
 * @author xt
 */
@Controller
public class LoginController extends BaseController{
	private static Logger logger = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private AccountService accountService;

	@Deprecated
	@RequiresRoles(value = { "assistant", "agency"}, logical = Logical.OR)
	@RequestMapping(value = "/account/switch", method = RequestMethod.GET)
	public String switchRole() {
		User user  = null;
		ShiroUser suser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
//		if(hasRole(SysConstants.ASSISTANT)){	//转为领导代理角色
//			if(suser.isLockSec==1){
//				throw new ServiceException("agency locked!");
//			}
//			user = accountService.swichAgencyRole(SysConstants.AGENCY);
//		}else if(hasRole(SysConstants.AGENCY)){	//转为秘书个人角色
//			user = accountService.swichAgencyRole(SysConstants.ASSISTANT);
//		}
//		if(user == null){
//            throwException(BusinessStatus.ERROR,"user switch error!");
//        }
//		user.setPlainPassword(suser.getPlainPassword());
//
//		SecurityUtils.getSubject().logout();
//
//	    UsernamePasswordToken token = new UsernamePasswordToken();
//	    token.setUsername(user.getLoginName());
//	    token.setPassword(user.getPlainPassword().toCharArray());
//		SecurityUtils.getSubject().login(token);

		return "redirect:/mobile/index";
	}



/*
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }
    @RequestMapping(value = "/login", method = RequestMethod.POST)
	public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
		return "login";
	}
	@RequestMapping(value="/logoutCas")
    public void logout(HttpServletResponse resp,HttpServletRequest requ) throws Exception {
		SecurityUtils.getSubject().logout();
		CookieUtil.clearCookie(resp, requ);

		resp.sendRedirect("login");
//        resp.sendRedirect(PropsUtil.getProperty(PropsKeys.SSO_CAS_SERVER_URL)
//        		+"/logout?service="+PropsUtil.getProperty(PropsKeys.SSO_CAS_SERVICE));
    }
*/



    @RequestMapping(value = "/loginjsp", method = RequestMethod.GET)
    public String loginjsp() {
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ResponseEntity<?> login(HttpServletResponse response) {
        Map<String,String> result = Maps.newHashMap();
        result.put("code", BusinessStatus.SESSION_INVALID);
        result.put("msg", "sessionInvalid");
        response.setHeader("sessionInvalid", "true");
        return new ResponseEntity(result ,HttpStatus.OK);
    }
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseEntity<?> fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
        model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
        Map<String,String> result = Maps.newHashMap();
        result.put("code", BusinessStatus.ERROR);
        result.put("msg", "login failure");
        return new ResponseEntity(result ,HttpStatus.OK);
    }
    @RequestMapping(value="/logoutCas")
    public ResponseEntity<?> logout(HttpServletResponse resp,HttpServletRequest requ) throws Exception {
        SecurityUtils.getSubject().logout();
        CookieUtil.clearCookie(resp, requ);

        return new ResponseEntity<Map<String,String>>(GetSuccMap() ,HttpStatus.OK);
    }

//	@RequestMapping(value="/mobilelogout")
//    public ResponseEntity<?> mobilelogout(HttpServletResponse resp,HttpServletRequest requ) throws Exception {
//		SecurityUtils.getSubject().logout();
//        CookieUtil.clearCookie(resp, requ);
//        
//		return new ResponseEntity<Map<String,String>>(GetSuccMap() ,HttpStatus.OK);
//    }
//	
//	
//	@RequestMapping(value = "/mobile/index", method = RequestMethod.GET)
//	public String index() {
//		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
//		Set<Role> roleSet = user.roleList;
//		for(Role role:roleSet){
//			if(!Validator.isNull(role.getDefaultUrl())){
//				return "redirect:"+role.getDefaultUrl();
//			}
//		}
//		
//		return "redirect:/#/articles";
//	}









}
